import Vue from 'vue'
import request from '@/utils/request/index.js'
import store from '@/store'

// 获取用户IM的token
export async function getImToken(){
  const { data } = await request({url: '/store/mini/im/getToKen',method: 'GET'},{isTransformResult: true})
  // 获取到用户的IM的token后连接IM
  Vue.prototype.$im.connect({ token: data.userToken }).then(user => {
    // 连接成功后获取到IM的userID后查询IM信息
    getImUserInfo(user.id).then(userInfo=>{
      userInfo.userToken = data.userToken
      store.commit('SET_IM_USERINFO', userInfo) // 存储于vuex
    })
  }).catch(error => {
    console.log('IM链接失败: ', error.code, error.msg);
  });
}

// 断开链接
export async function disconnectIm(params) {
  store.commit('SET_IM_USERINFO', {})
  Vue.prototype.$im.disconnect().then(() => console.log('断开链接成功'));
}


// 获取用户IM信息
export async function getImUserInfo(id){
  const { data } = await request({url: `/store/mini/im/getImUserInfo?accountId=${id}`,method: 'GET'})
  return data
}

// 获取用户消息为读数，用于展示红点 包含免打扰会话，包含私聊加系统
export function getTotalUnreadCount(){
  try {
    const conversationTypes = [Vue.prototype.$RongIMLib.CONVERSATION_TYPE.PRIVATE,Vue.prototype.$RongIMLib.CONVERSATION_TYPE.SYSTEM] // 私聊加系统
    Vue.prototype.$im.Conversation.getTotalUnreadCount(true,conversationTypes).then(res=>{
      store.commit('SET_IM_UNREADCOUNT', res)
    })
  } catch (error) {
    console.log(error,'更新Im未读数报错');
  }
}